package util

import (
	"bytes"
	"context"
	"encoding/json"
	"net/http"
	"pkgm/config"
	"time"
)

// 定义一个HTTPClient结构体，可以在这里添加更多的字段，例如超时时间、重试次数等
type HTTPClient struct {
	client *http.Client
}

// 创建一个新的HTTPClient实例
func NewHTTPClient() *HTTPClient {
	return &HTTPClient{
		client: &http.Client{
			Timeout: 10 * time.Second, // 设置默认超时时间为10秒
		},
	}
}

// Get 发送GET请求
func (c *HTTPClient) Get(url string) (*http.Response, error) {
	req, err := http.NewRequest("GET", config.SERVER_URL+"/api/"+url, nil)
	if err != nil {
		return nil, err
	}
	return c.do(req)
}

// Post 发送POST请求
func (c *HTTPClient) Post(url string, body interface{}) (*http.Response, error) {
	jsonData, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", config.SERVER_URL+"/api/"+url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	return c.do(req)
}

// do 执行HTTP请求
func (c *HTTPClient) do(req *http.Request) (*http.Response, error) {
	resp, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

// 使用上下文取消请求
func (c *HTTPClient) DoWithContext(ctx context.Context, req *http.Request) (*http.Response, error) {
	req = req.WithContext(ctx)
	return c.do(req)
}
